/**
 * PixelSampler.java ##copyright## This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public License as published by the Free
 * Software Foundation; either version 2.1 of the License, or (at your option) any later version.
 * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
 * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details. You should have received a copy of the GNU Lesser
 * General Public License along with this library; if not, write to the Free Software Foundation,
 * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 * 
 * @author ##author##
 * @modified ##date##
 * @version ##version##
 */
package fiveagon.color;

import processing.core.PImage;
import toxi.color.ColorList;
import toxi.color.HistEntry;
import toxi.color.Histogram;

public class PixelSampler {
  private final int[] pixels;

  public PixelSampler(int[] pixels) {
    this.pixels = pixels;
  }

  public PixelSampler(PImage image) {
    PImage tempImage = image.get();
    tempImage.loadPixels();
    this.pixels = tempImage.pixels;
  }

  public ColorList toColorList(int numColors) {
    return toColorList(numColors, 0.1f, true);
  }

  public ColorList toColorList(int numColors, float tolerance, boolean blendingOn) {
    Histogram histogram = Histogram.newFromARGBArray(pixels, pixels.length, tolerance, blendingOn);
    ColorList palette = new ColorList();

    for (HistEntry histentry : histogram) {
      palette.add(histentry.getColor());
      if (palette.size() >= numColors) {
        break;
      }
    }

    return palette;
  }

  public int[] toArray(int numColors, float tolerance, boolean blendingOn) {
    return toColorList(numColors, tolerance, blendingOn).toARGBArray();
  }
}
